window.genesis || (window.genesis = {});

(function ($) {
    var _WIN = window;
    var _PARENT = _WIN.parent;

    var funs;
    if(_WIN != _PARENT) {
        do {
            _WIN = _PARENT;
            _PARENT = _WIN.parent;
        } while (_PARENT != _WIN);


        var showLoading = _WIN.genesis["showLoading"];
        var hideLoading = _WIN.genesis["hideLoading"];
        funs = (showLoading && hideLoading) ? {"showLoading": showLoading, "hideLoading": hideLoading} : null;
    }

    funs = funs || (function() {
        var html = '<div style="position: fixed;left:0;top: 0;width: 100%;height: 100%;z-index: 9999;display: none;">\
                    <div style="position: absolute;left:0;top: 0;width: 100%;height: 100%;background: black;opacity: 0.5;z-index: 1;">&nbsp;</div>\
                    <div style="position:relative;width: 220px;padding: 50px 0;text-align:center;background:white;margin: auto;margin-top: 200px;z-index: 2;">Loading&hellip;</div>\
                </div>';


        var result = {
            "modal": false,
            count: 0,
            id: 0
        };


        var $loading = {
            show: function () {
                var $l;
                if(!result["modal"]){
                    $l = $(html).appendTo("body");
                    result["modal"] = $l;
                }else {
                    $l = result["modal"];
                }

                result.count += 1;
                if (result.count == 1) {
                    result.id = setTimeout(function () {
                        $l.show();
                    }, 300);
                }
            },
            hide: function () {
                var $l = result["modal"];
                if(!$l) {
                    return;
                }
                result.count -= 1;
                if (result.count <= 0) {
                    result.count = 0;
                    clearTimeout(result.id);
                    $l.hide();
                }
            }
        };

        return {
            showLoading: function () {
                $loading.show();
            },
            hideLoading: function () {
                $loading.hide();
            }
        };
    })();

    window.genesis = $.extend(window.genesis, funs);
})(jQuery);
